using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Nix.PBeM.Engine.Report
{
	public class TextFileWrap
	{
		public static void Do(string sourceFile, string targetFile, int maxLength)
		{
			StreamReader i = File.OpenText(sourceFile);
			StreamWriter o = File.CreateText(targetFile);
			while ( ! i.EndOfStream )
			{
				string curLine = i.ReadLine();
				if (curLine.Length <= maxLength)
				{
					o.WriteLine(curLine);
					continue;
				}
				string tab = string.Empty;
				for(int t = 0; t < curLine.Length; t++)
				{
					if (curLine[t] != ' ' && curLine[t] != '\t')
					{
						if (t > 0)
							tab = curLine.Substring(0, t);
						break;
					}
				}
				do
				{
					int pos = curLine.Substring(0, maxLength).LastIndexOfAny(new char[]{' ', '\t'});
					if (pos == -1)
						pos = maxLength - 1;
					o.WriteLine(curLine.Substring(0, pos + 1));
					curLine = tab + Engine.Instance.ReportIdent + curLine.Substring(pos + 1);
				} while (curLine.Length > maxLength);
				if (curLine.Length > 0)
					o.WriteLine(curLine);
			}
			i.Close();
			o.Close();
		}
	}
}
